package com.help10000.rms.ui.utils

import android.content.Context
import com.amir.common.utils.LogUtils
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.default
import id.zelory.compressor.constraint.destination
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.size
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileNotFoundException

object ImageCompressor {

    /**
     * 异步压缩图片，不修改原图，返回压缩后的 File 对象
     * @param context Context
     * @param sourceFile 原始图片文件
     * @param quality 压缩质量（默认 80）
     */
    fun compressAsync(
        context: Context,
        sourceFile: File,
        quality: Int = 80
    ): Single<File> {
        return Single.create { emitter ->
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    // 修改 Compressor 配置，指定自定义目录（如外部存储私有目录）,需要启动应用的时候清理这个文件夹
                    LogUtils.I("TrackCom compressAsync", "sourceFile: ${sourceFile.path}, size: ${sourceFile.length()}")

                    // ✅ 如果图片小于等于 200KB，直接返回原图
                    if (sourceFile.length() <= 204_800) {
                        LogUtils.I("TrackCom compressAsync", "skip compress, size <= 200KB")
                        emitter.onSuccess(sourceFile)
                        return@launch
                    }

                    val compressedDir = File(context.getExternalFilesDir(null), "shabei_compressed_images"
                            +File.separator
                            +sourceFile.name)

                    LogUtils.I(
                        "TrackCom compressAsync",
                        "compressedDir: ${compressedDir.path}"
                    )
                    val compressed = Compressor.compress(context, sourceFile) {
                        default()
                        quality(quality)
                        size(2_097_152) // 限制最大2MB
                        destination(compressedDir)  // 指定稳定存储路径
                    }

                    LogUtils.I(
                        "TrackCom compressAsync",
                        "compressed: ${compressed.path}"
                    )
                    if (compressed.exists()) {
                        emitter.onSuccess(compressed)
                    } else {
                        emitter.onError(FileNotFoundException("压缩文件不存在"))
                    }

                } catch (e: Exception) {
                    emitter.onError(e)
                }
            }
        }
    }

    /**
     * 清空压缩图片的临时目录
     * @param context Context
     */
    fun clearCompressedImages(context: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val compressedDir = File(context.getExternalFilesDir(null), "shabei_compressed_images")
                if (compressedDir.exists()) {
                    compressedDir.deleteRecursively() // 递归删除目录及内容
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}
